
import * as qs from 'querystring';
export const outerToken = 'gms-jwt-token';
export const outerSignature = 'gms-outer-signature';

export const generateRequestId = () => {
    const id = `d${Date.now()}-t${Math.random()}`;
    return id;
};

function checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response;
    }

    const error = new Error(response.statusText);
    error.response = response;
    throw error;
}

export async function load(url, options) {
    const resp = await fetch(url, { credentials: 'include', ...options });
    return resp.text();
}
/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default async function request(url, options) {
    const headers = options.headers || {};
    headers['request-id'] = generateRequestId();
    const token = sessionStorage.getItem(outerToken);
    const signature = sessionStorage.getItem(outerSignature);
    if (token) {
        headers[outerToken] = token;
    }
    if (signature) {
        headers[outerSignature] = signature;
    }
    options.headers = headers;
    const response = await fetch(`${url}`, { credentials: 'include', ...options });
    checkStatus(response);
    const resp = await response.json();
    const { ret, data } = resp;
    if (0 !== ret) {
        if (401 === ret) {
            gotoLogin();
        } else {
            throw resp;
        }
    } else {
        // checkIsUnlogin(url, resp);
    }
    return data;
}

export function querystring(data = {}) {
    return qs.stringify(data);
}

export function get(baseUrl, data = {}, options = {}) {
    const query = querystring(data);
    const url = `${baseUrl}?${query}`;
    return request(url, Object.assign({}, options));
}

export function post(url, data = {}, options = {}) {
    let headers = {};
    switch (true) {
        case data instanceof FormData:
            headers = {
                ...headers,
                'x-csrf-token': getCookie('csrfToken'),
            };
            break;
        case 'string' !== typeof data:
            data = JSON.stringify(data);
            headers = {
                ...headers,
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'x-csrf-token': getCookie('csrfToken'),
            };
            break;
        default:
    }
    const body = data;
    return request(url, Object.assign({}, options, { method: 'post', headers, body }));
}

export function getCookie(name) {
    const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
    const arr = document.cookie.match(reg);
    if (arr) {
        return decodeURIComponent(arr[2]);
    } else {
        return null;
    }
}

request.get = get;
request.post = post;
